export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 
 * @param {*stringToBuffer} str 
 *  将字符串转成 buffer 参数
 */
export const stringToBuffer = function (str, en) {
  // 首先将字符串转为16进制
  if (!str) {
    return new Uint8Array().buffer;
  }

  let val = '';
  for (let i = 0; i < str.length; i++) {
    if (val === '') {
      val = str.charCodeAt(i).toString(16)
    } else {
      val += ',' + str.charCodeAt(i).toString(16)
    }
  }
  if (en)
    val = `${en},${val}`
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  })).buffer
}


// let records = [{
//   id: stringToBuffer(params.id),
//   payload: stringToBuffer(params.payload + ""),
//   type: stringToBuffer(params.type),
//   tnf: params.tnf || 1
// }];

/**
 * 
 * @param {*} arr 
 * 将读取的数据转换成字符串
 */
export function byteToString(arr) {
  if (typeof arr === 'string') {
    return arr;
  }
  var str = '',
    _arr = arr;
  for (var i = 0; i < _arr.length; i++) {
    var one = _arr[i].toString(2),
      v = one.match(/^1+?(?=0)/);
    if (v && one.length == 8) {
      var bytesLength = v[0].length;
      var store = _arr[i].toString(2).slice(7 - bytesLength);
      for (var st = 1; st < bytesLength; st++) {
        store += _arr[st + i].toString(2).slice(2);
      }
      str += String.fromCharCode(parseInt(store, 2));
      i += bytesLength - 1;
    } else {
      str += String.fromCharCode(_arr[i]);
    }
  }
  return str;
}

export function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

// NFCAdapter.onDiscovered((res) => {
//   console.log("onDiscovered res=>", res);
//   if (!res.techs.includes(NFCAdapter.tech.ndef)) {
//     return
//   }
//   let aid = parseInt(ab2hex(res.id), 16);
//   // {id: ArrayBuffer(4), techs: Array(3)}
//   if (res.messages) {
//     let cordsArray = res.messages[0].records;
//     cordsArray.find((item) => {
//       let payload = byteToString(new Uint8Array(item.payload))
//       let id = byteToString(new Uint8Array(item.id))
//       let type = byteToString(new Uint8Array(item.type))
//     })
//   }
// });